package com.jack.helloworld.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * 存储工具类（xml）
 */
public class SharedPreferenceHelper {
	public static final int BOOLEAN_VALUE = 1;
	public static final int STRING_VALUE = 2;
	public static final int INTEGER_VALUE = 3;
	public static final int LONG_VALUE = 4;
	public static final int FLOAT_VALUE = 5;

	public static Editor getEditor(Context context, String dbName) {
		SharedPreferences settings = context.getSharedPreferences(dbName,
				Context.MODE_PRIVATE);
		Editor editor = settings.edit();
		return editor;
	}

	public static SharedPreferences getSharedPreferences(Context context,
                                                         String dbName) {
		return context.getSharedPreferences(dbName, Context.MODE_PRIVATE);
	}

	public static boolean write(Context context, String dbName, String key,
                                Object value) {
		SharedPreferences settings = context.getSharedPreferences(dbName,
				Context.MODE_PRIVATE);
		Editor editor = settings.edit();

		if (value instanceof Integer) {
			editor.putInt(key, (Integer) value);
			editor.commit();
			return true;

		} else if (value instanceof String) {
			editor.putString(key, (String) value);
			editor.commit();
			return true;
		} else if (value instanceof Boolean) {
			editor.putBoolean(key, (Boolean) value);
			editor.commit();
			return true;
		} else if (value instanceof Long) {
			editor.putLong(key, (Long) value);
			editor.commit();
			return true;
		} else if (value instanceof Float) {
			editor.putFloat(key, (Float) value);
			editor.commit();
			return true;
		} else {
			return false;
		}

	}

	public static Object read(Context context, String dbName, String key,
                              int mode) {
		SharedPreferences settings = context.getSharedPreferences(dbName,
				Context.MODE_PRIVATE);
		if (mode == BOOLEAN_VALUE) {
			boolean value = settings.getBoolean(key, false);
			return value;
		} else if (mode == STRING_VALUE) {
			String value = settings.getString(key, "");
			return value;
		} else if (mode == INTEGER_VALUE) {
			int value = settings.getInt(key, 0);
			return value;
		} else if (mode == LONG_VALUE) {
			Long value = settings.getLong(key, 0);
			return value;
		} else if (mode == FLOAT_VALUE) {
			float value = settings.getFloat(key, 0);
			return value;
		} else {
			return null;
		}

	}

}
